package com.lib.utils;

import android.content.Context;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * @author 一叶丶枫凌
 * Created on 2016-12-06 15:09
 */
public class AssetsUtils {

    /**
     * 获取Assets中的文本
     *
     * @param context  上下文
     * @param fileName 文本名称
     * @return
     */
    public static String getString(Context context, String fileName) {

        String s = "";

        if (fileName != null) {
            String path = "json/" + fileName;
            InputStream is = null;
            try {
                is = context.getAssets().open(path);
                s = readTextFile(is);
            } catch (IOException e) {
                s = "";
            } finally {
                CloseUtils.closeIOQuietly(is);
            }
        }
        return s;
    }

    /**
     * 从输入流中获取文本
     *
     * @param is 文本输入流
     * @return
     */
    private static String readTextFile(InputStream is) {

        StringBuilder readStr = new StringBuilder();
        BufferedReader br = null;

        try {
            br = new BufferedReader(new InputStreamReader(is, "UTF-8"));

            while (br.ready()) {

                readStr.append(br.readLine()).append("\n");
            }
        } catch (Exception e) {
            return null;
        } finally {
            CloseUtils.closeIOQuietly(br, is);
        }
        return readStr.toString();
    }
}